package com.example.icedcap.topeka_fake.fragment;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.example.icedcap.topeka_fake.R;
import com.example.icedcap.topeka_fake.activity.QuizActivity;
import com.example.icedcap.topeka_fake.adapter.CategoryAdapter;
import com.example.icedcap.topeka_fake.helper.TransitionHelper;

/**
 * Author: doushuqi
 * Date: 15/7/13
 * Time: 下午2:49
 * Email: shuqi.dou@singuloid.com
 */
public class CategorySelectorFragment extends Fragment {

    private CategoryAdapter mCategoryAdapter;

    public static CategorySelectorFragment newInstance() {
        return new CategorySelectorFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_categories, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        setUpQuizGrid((GridView) view.findViewById(R.id.categories));
        super.onViewCreated(view, savedInstanceState);
    }

    private void setUpQuizGrid(GridView categoriesView) {
        categoriesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                performStartQuizActivity(view, position);
            }
        });
        mCategoryAdapter = new CategoryAdapter(getActivity());
        categoriesView.setAdapter(mCategoryAdapter);

    }

    @Override
    public void onResume() {
        mCategoryAdapter.notifyDataSetChanged();
        super.onResume();
    }

    private void performStartQuizActivity(View v, int position) {
        final Activity activity = getActivity();
        final Pair[] pairs = TransitionHelper.createSafeTransitionParticipants(activity, true,
                new Pair<>(v, getString(R.string.transition_toolbar)));
        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(activity, pairs);
        Intent intent = QuizActivity.starter(getActivity(), mCategoryAdapter.getItem(position));
        activity.startActivity(intent, options.toBundle());
    }
}
